package com.corx.network.mysqlstorage.common;

import cn.hutool.core.util.ObjectUtil;

/**
 * @author gx
 * @version 1.0.0
 */
public class PageQuery {
    /**
     * 当前页
     */
    private Integer pageNum;
    /**
     * 每页记录数
     */
    private Integer pageSize;

    private String sortFields; // 示例：name,create_time
    private String sortOrders; // 示例：asc,desc


    /**
     * 当前记录起始索引 默认值
     */
    public static final int DEFAULT_PAGE_NUM = 1;

    /**
     * 每页显示记录数 默认值 默认查1000
     */
    public static final int DEFAULT_PAGE_SIZE = 1000;


    public boolean hasSort() {
        return sortFields != null && !sortFields.isEmpty();
    }

    public String orderBy() {
        if (!hasSort()) {
            return "";
        }

        String[] fields = sortFields.split(",");
        String[] orders = sortOrders != null ? sortOrders.split(",") : new String[0];

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fields.length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(fields[i].trim());
            if (i < orders.length) {
                sb.append(" ").append(orders[i].trim().toUpperCase());
            } else {
                sb.append(" ASC");
            }
        }
        return sb.toString();
    }


    public Integer getPageNum() {
        return ObjectUtil.defaultIfNull(pageNum, DEFAULT_PAGE_NUM);
    }

    public void setPageNum(Integer page) {
        this.pageNum = page;
    }

    public Integer getPageSize() {
        return ObjectUtil.defaultIfNull(pageSize, DEFAULT_PAGE_SIZE);

    }

    public void setPageSize(Integer size) {
        this.pageSize = size;
    }


    public Integer getOffset() {
        int p = getPageNum();
        return (p - 1) * getPageSize();
    }

    public String getSortFields() {
        return sortFields;
    }

    public void setSortFields(String sortFields) {
        this.sortFields = sortFields;
    }

    public String getSortOrders() {
        return sortOrders;
    }

    public void setSortOrders(String sortOrders) {
        this.sortOrders = sortOrders;
    }
}
